public class Solution919 {

    public static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    int cur=0;
    TreeNode t;

    public Solution919(TreeNode root) {
        t=root;
        dfs(root);
    }

    private void dfs(TreeNode root) {
        if (root==null){
            return;
        }
        cur++;
        dfs(root.left);
        dfs(root.right);
    }

    public int insert(int val) {
        cur++;
        TreeNode treeNode=t;
        TreeNode last=t;
        int t=Integer.numberOfLeadingZeros(cur);
        for (int i=30-t;i>=1;i--){
            last=treeNode;
            if ((cur&(1<<i))==0){
                treeNode=treeNode.left;
            }else{
                treeNode=treeNode.right;
            }
        }
        last=treeNode;
        if ((cur&1)==0){
            last.left=new TreeNode(val);
        }else{
            last.right=new TreeNode(val);
        }
        return last.val;
    }

    public TreeNode get_root() {
        return t;
    }

    public static void main(String[] args) {
        Solution919 solution919=new Solution919(new TreeNode(1,new TreeNode(2),null));
        System.out.println(solution919.insert(3));
        System.out.println(solution919.insert(4));
        System.out.println(solution919.get_root().left.left.val);
    }
}
